package com.aigou.admin.aigouspringboot.service.impl;

import com.aigou.admin.aigouspringboot.common.Constants;
import com.aigou.admin.aigouspringboot.context.BaseContext;
import com.aigou.admin.aigouspringboot.entity.ShopCart;
import com.aigou.admin.aigouspringboot.entity.User;
import com.aigou.admin.aigouspringboot.entity.dto.UserQueryDTO;
import com.aigou.admin.aigouspringboot.entity.vo.UserVO;
import com.aigou.admin.aigouspringboot.exception.BusinessException;
import com.aigou.admin.aigouspringboot.mapper.ShopCartMapper;
import com.aigou.admin.aigouspringboot.mapper.UserMapper;
import com.aigou.admin.aigouspringboot.service.UserService;
import com.aigou.admin.aigouspringboot.utils.JSONUtils;
import com.aigou.admin.aigouspringboot.utils.JWTUtils;
import com.aigou.admin.aigouspringboot.utils.MD5Util;
import com.aigou.admin.aigouspringboot.utils.RandomUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author Mr.LiFuXing
 * @Date 2024/12/10 20:21
 * @Title UserServiceImpl
 * @Package com.aigou.admin.aigouspringboot.service.impl
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ShopCartMapper shopCartMapper;

    /**
     * 用户登录
     *
     * @return i
     */
    @Override
    public UserVO login(User user, HttpServletRequest httpServletRequest, HttpServletResponse response) {

        user.setUserPwd(MD5Util.encryptToMD5(user.getUserPwd()));
        user = userMapper.login(user);
        if (user == null) {
            throw new RuntimeException(Constants.LOGIN_ERROR);
        }
        httpServletRequest.getSession().setAttribute(Constants.USER_SESSION, user);

        String userJson = JSONUtils.toJSON(user);
        String jwt = JWTUtils.createJWT(userJson);

        return UserVO.builder()
                .userId(user.getUserId())
                .userName(user.getUserName())
                .userType(user.getUserType())
                .token(jwt).
                build();
    }

    @Override
    public int register(User user) {
        if (user.getUserName() == null && user.getUserPwd() == null) {
            throw new RuntimeException();
        }

        user.setUserId(RandomUtil.getRandomNumber());
        user.setUserType(Constants.USER_TYPE_USER);
        return userMapper.insertSelective(user);
    }

    @Override
    public UserVO userLogin(User user, HttpServletRequest httpServletRequest) {

        if (user.getUserName() == null && user.getUserPwd() == null) {
            throw new RuntimeException();
        }
        user = userMapper.selectUser(user);
        BaseContext.setUserId(user.getUserId());
        httpServletRequest.getSession().setAttribute(Constants.USER_SESSION, user);
        String userJson = JSONUtils.toJSON(user);
        String jwt = JWTUtils.createJWT(userJson);

        // 查询用户是否有购物车
        ShopCart shopCart = shopCartMapper.selectCartByUserId(user.getUserId());

        // 用户没有购物车
        if (shopCart == null) {
            ShopCart cart = new ShopCart();
            cart.setId(RandomUtil.getRandomNumber());
            cart.setCartId(RandomUtil.getRandomNumber());
            cart.setUserId(user.getUserId());
            shopCartMapper.insertSelective(cart);
        }
        return UserVO.builder()
                .userId(user.getUserId())
                .userName(user.getUserName())
                .userType(user.getUserType())
                .token(jwt).
                build();
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {

        return (User) request.getSession().getAttribute(Constants.USER_SESSION);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param current      当前页
     * @param userQueryDTO dto
     * @return info
     */
    @Override
    public PageInfo<User> selectUserListByPage(Integer current, UserQueryDTO userQueryDTO) {
        // 分页插件，开启分页
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        // 查询所有用户信息
        List<User> userList = userMapper.selectUserByCondition(userQueryDTO);
        // 把userList放入返回分页信息
        return new PageInfo<>(userList);
    }


    /**
     * 根据id删除用户
     *
     * @param id id
     * @return 1
     */
    @Override
    public int deleteById(String id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据id查询用户信息
     *
     * @param id id
     * @return user
     */
    @Override
    public User selectById(String id) {

        return userMapper.selectByPrimaryKey(id);
    }


    /**
     * 编辑用户信息
     *
     * @param user user
     * @return 1
     */
    @Override
    public int edit(User user) {

        return userMapper.updateByPrimaryKeySelective(user);
    }


    /**
     * 添加用户信息
     *
     * @param user
     * @return
     */
    @Override
    public int save(User user) {
        return userMapper.insertSelective(user);
    }


}
